from sklearn.linear_model import RidgeCV
from sklearn.metrics import r2_score
import numpy as np

# 1. 设置超参数（正则参数）范围
alphas = [0.01, 0.1, 1, 10, 100]


def visual_weightCoef(x_train, y_train, x_test, y_test):
    # 2. 生成一个RidgeCV实例
    ridge = RidgeCV(alphas=alphas, store_cv_values=True)

    # 3. 模型训练
    ridge.fit(x_train, y_train)
    # 4. 预测
    y_test_pred_ridge = ridge.predict(x_test)
    y_train_pred_ridge = ridge.predict(x_train)
    # 评估，使用r2_score评价模型在测试集和训练集上的性能
    print('The r2 score of RidgeCV on test is', r2_score(y_test, y_test_pred_ridge))
    print('The r2 score of RidgeCV on train is', r2_score(y_train, y_train_pred_ridge))

    mse_mean = np.mean(ridge.cv_values_, axis=0)
    return mse_mean, alphas, ridge.alpha_, ridge.coef_


